<template>
  <div class="verification-code">
    <input v-for="(digit, index) in digits" :key="index" ref="inputs" v-model="digits[index]" type="text" maxlength="1"
      pattern="[0-9]*" inputmode="numeric" @input="handleInput(index, $event)"
      @keydown.delete="handleDelete(index, $event)" @focus="handleFocus" class="code-input" />
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'

const props = defineProps({
  length: {
    type: Number,
    default: 6
  }
})

const emit = defineEmits(['complete'])

const digits = ref(Array(props.length).fill(''))
const inputs = ref([])

// 处理输入
const handleInput = (index, event) => {
  const value = event.target.value

  // 只允许数字
  if (!/^\d*$/.test(value)) {
    digits.value[index] = ''
    return
  }

  // 自动聚焦下一个输入框
  if (value && index < props.length - 1) {
    nextTick(() => {
      inputs.value[index + 1].focus()
    })
  }

  // 检查是否所有数字都已输入
  checkCompletion()
}

// 处理删除键
const handleDelete = (index, event) => {
  if (event.key === 'Delete' || event.key === 'Backspace') {
    // 如果当前框为空，则删除前一个框的内容并聚焦
    if (!digits.value[index] && index > 0) {
      digits.value[index - 1] = ''
      nextTick(() => {
        inputs.value[index - 1].focus()
      })
    }
  }
}

// 处理聚焦事件，选中所有文本以便替换
const handleFocus = (event) => {
  event.target.select()
}

// 检查是否所有数字都已输入
const checkCompletion = () => {
  const code = digits.value.join('')
  if (code.length === props.length) {
    emit('complete', code)
  }
}

// 暴露方法供外部调用
defineExpose({
  clear: () => {
    digits.value = Array(props.length).fill('')
    nextTick(() => {
      if (inputs.value[0]) {
        inputs.value[0].focus()
      }
    })
  },
  getCode: () => digits.value.join('')
})
</script>

<style scoped>
.verification-code {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}

.code-input {
  width: 50px;
  height: 50px;
  text-align: center;
  font-size: 24px;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
}

.code-input:focus {
  border-color: var(--el-border-color);
  box-shadow: 0 0 0 2px var(--el-color-primary-light-5)
}
</style>
